package com.goldze.mvvmhabit.ui.tab_bar.fragment.leave;

import android.app.Application;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableField;
import android.databinding.ObservableList;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.goldze.mvvmhabit.R;
import com.goldze.mvvmhabit.data.DemoRepository;
import com.goldze.mvvmhabit.entity.response.GetBannerListResponseEntity;
import com.goldze.mvvmhabit.entity.response.GetTypeListResponseEntity;
import com.goldze.mvvmhabit.utils.RetrofitClient;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class LeaveViewModel extends BaseViewModel<DemoRepository> {

    public SingleLiveEvent<List<String>> bannerUrl = new SingleLiveEvent<>();

    public SingleLiveEvent<List<String>> typeList = new SingleLiveEvent<>();

    public SingleLiveEvent<String> name = new SingleLiveEvent<>();

    public SingleLiveEvent<String> departName = new SingleLiveEvent<>();

    public SingleLiveEvent<String> startTimeEvent = new SingleLiveEvent<>();
    public ObservableField<String> startTimeValue = new ObservableField<>();

    public SingleLiveEvent<String> endTimeEvent = new SingleLiveEvent<>();
    public ObservableField<String> endTimeValue = new ObservableField<>();

    public ObservableField<String> reason = new ObservableField<>("");

    public SingleLiveEvent<List<String>> imageList = new SingleLiveEvent<>();

    public ObservableField<String> typeId = new ObservableField<>("");

    public SingleLiveEvent selectAlbum = new SingleLiveEvent<>();

    public ArrayList<GetTypeListResponseEntity> typeListEntity = null;

    //给RecyclerView添加ObservableList
    public static ObservableList<LeaveItemViewModel> observableList = new ObservableArrayList<>();

    public ObservableList<LeaveItemViewModel> uploadList = new ObservableArrayList<>();

    //给RecyclerView添加ItemBinding
    public ItemBinding<LeaveItemViewModel> itemBinding = ItemBinding.of(com.goldze.mvvmhabit.BR.viewModel, R.layout.item_leave_imagelist);

    public String selectId = "";
    public String imageurl = "";

    public String startTimeStr = "";
    public String endTimeStr = "";

    public LeaveViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    public BindingCommand leaveEvent = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uploadList.clear();
            uploadList.addAll(observableList);
            imageurl = "";
            upLoadImg();
        }
    });

    public BindingCommand startTimeOnClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startTimeEvent.setValue("");
        }
    });

    public BindingCommand endTimeOnClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            endTimeEvent.setValue("");
        }
    });

    public void upLoadImg() {
        if (TextUtils.isEmpty(startTimeStr)) {
            ToastUtils.showShort("请输入开始时间！");
            return;
        }
        if (TextUtils.isEmpty(endTimeStr)) {
            ToastUtils.showShort("请输入结束时间！");
            return;
        }
        if (TextUtils.isEmpty(reason.get())) {
            ToastUtils.showShort("请输入事由！");
            return;
        }
        if ((uploadList.size() > 0 && uploadList.get(0).entity.get() == null) || uploadList.size() == 0) {
            getAddLeaveForm(startTimeStr, endTimeStr, reason.get(), selectId, imageurl, "");
            return;
        }
        model.uploadImg(uploadList.get(0).entity.get())
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new Consumer<BaseResponse<String>>() {
                    @Override
                    public void accept(BaseResponse<String> response) throws Exception {
                        //请求成功
                        if (response.isSuccess()) {
                            imageurl = imageurl + response.getResponse();
                        }
                        uploadList.remove(0);
                        upLoadImg();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        dismissDialog();
                    }
                });
    }


    public void getAddLeaveForm(String starTime, String endTime, String reason, String typeId, String image, String address) {
        model.addLeaveForm(starTime, endTime, reason, typeId, image, address)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new Consumer<BaseResponse<String>>() {
                    @Override
                    public void accept(BaseResponse<String> response) throws Exception {
                        //请求成功
                        if (response.isSuccess()) {
                            ToastUtils.showShort(response.getResponse());
                            LeaveViewModel.this.startTimeStr = "";
                            LeaveViewModel.this.startTimeValue.set("");
                            LeaveViewModel.this.endTimeStr = "";
                            LeaveViewModel.this.endTimeValue.set("");
                            LeaveViewModel.this.reason.set("");
                            LeaveViewModel.this.imageurl = "";
                            clearImageData();
                        } else {
                            ToastUtils.showShort("申请失败！");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        dismissDialog();
                    }
                });
    }

    public void clearImageData() {
        observableList.clear();
        addDefaultImgaeList(null);
    }

    public void selectTypeId(int position) {
        if (typeListEntity != null) {
            selectId = typeListEntity.get(position).getId();
        }
    }

    //获取请假类型
    public void getTypeList() {
        model.getTypeList()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse<ArrayList<GetTypeListResponseEntity>>>() {
                    @Override
                    public void accept(BaseResponse<ArrayList<GetTypeListResponseEntity>> response) throws Exception {
                        //请求成功
                        if (response.isSuccess()) {
                            List<String> list = new ArrayList<String>();
                            for (GetTypeListResponseEntity item : response.getResponse()) {
                                list.add(item.getName());
                            }
                            typeList.setValue(list);
                            typeListEntity = response.getResponse();
                            if (typeListEntity != null && typeListEntity.size() > 0) {
                                selectId = typeListEntity.get(0).getId();
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                    }
                });
    }

    public void getGetBannerList() {
        model.getGetBannerList()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse<ArrayList<GetBannerListResponseEntity>>>() {
                    @Override
                    public void accept(BaseResponse<ArrayList<GetBannerListResponseEntity>> response) throws Exception {
                        //请求成功
                        if (response.isSuccess()) {
                            List<String> list = new ArrayList<String>();
                            for (GetBannerListResponseEntity item : response.getResponse()) {
                                list.add(RetrofitClient.baseUrl + item.getUrl());
                            }
                            bannerUrl.setValue(list);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                    }
                });
    }

    public int getItemPosition(LeaveItemViewModel mLeaveItemViewModel) {
        return observableList.indexOf(mLeaveItemViewModel);
    }

    public void setStartTime(String startTime) {
        this.startTimeStr = startTime;
    }

    public void setEndTime(String endTime) {
        this.endTimeStr = endTime;
    }

    public void addDefaultImgaeList(String path) {
        LeaveItemViewModel mLeaveItemViewModel = new LeaveItemViewModel(this, path);
        if (observableList.size() == 9 && observableList.get(8).entity.get() == null) {
            observableList.remove(8);
            observableList.add(8, mLeaveItemViewModel);
        } else {
            if (path == null) {
                for (LeaveItemViewModel item : observableList) {
                    if (item.entity.get() == null) {
                        return;
                    }
                }
            }
            if (observableList.size() > 0) {
                observableList.add(observableList.size() - 1, mLeaveItemViewModel);
            } else {
                observableList.add(mLeaveItemViewModel);
            }
        }
    }

    public void addDefaultLastData() {
        LeaveItemViewModel mLeaveItemViewModel = new LeaveItemViewModel(this, null);
        observableList.add(mLeaveItemViewModel);
    }

    public void showAlbum() {
        selectAlbum.setValue(null);
    }
}
